package com.meida.mdtj.admin.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.oauth2.OpenOAuth2ClientProperties;
import com.meida.common.utils.ConvertUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.service.BaseRoleService;
import com.meida.module.system.client.entity.SysCompany;
import com.meida.module.system.client.entity.SysDept;
import com.meida.module.system.provider.service.SysCompanyService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * 用户列表扩展
 *
 * @author zyf
 */
@Component
@AllArgsConstructor
public class AdminUserListHandler implements PageInterceptor<BaseUser> {

    private final BaseRoleService roleService;

    private final RedisTokenStore redisTokenStore;

    private final OpenOAuth2ClientProperties clientProperties;
    @Override
    public void prepare(CriteriaQuery cq, PageParams pageParams, EntityMap params) {
        cq.select(BaseUser.class, "*");
        cq.select(SysDept.class, "deptName");
        cq.select(SysCompany.class, "companyName");
        cq.eq(SysDept.class,"deptId");
        cq.eq(SysCompany.class,"companyId");
        //平台用户类型
        cq.eq("userType", 1);
        cq.createJoin(SysDept.class);
        cq.createJoin(SysCompany.class);
    }

    @Override
    public void complete(CriteriaQuery<BaseUser> cq, List<EntityMap> result, EntityMap extra) {


        for (EntityMap entityMap : result) {
            Long userId=entityMap.getLong("userId");
            String userName=entityMap.get("userName");
            Collection<OAuth2AccessToken> accessTokens = redisTokenStore.findTokensByClientIdAndUserName(clientProperties.getOauth2().get("admin").getClientId(), userName);
            Integer onLineNum=0;
            if(FlymeUtils.isNotEmpty(accessTokens)){
                onLineNum=1;
            }
            entityMap.put("onLine", onLineNum);
            List<String> roleNames=roleService.selectRoleNamesByUserId(userId);
            entityMap.put("roleNames", ConvertUtils.listToString(roleNames));
        }
    }
}
